package homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/18 14:03
 */
public class Homework01Server {

    public static void main(String[] args) throws IOException {

        //1.服务端在9999端口监听
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听，等待客户端连接");

        //2.当没有客户端连接9999端口时，程序会阻塞，直到有客户端建立连接
        //当有客户端建立连接，返回一个socket对象
        //多个(不同的客户端建立连接)，返回不同的socket对象
        Socket socket = serverSocket.accept();

        //3.通过socket.getInputStream()得到和socket相关的输入流对象,读取客户端写入到数据通道的数据，进行显示
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println("问题是" + s);
        String answer ;
        if("name".equals(s)){
            answer = "我是nova";
        }else if("hobby".equals(s)){
            answer = "编写java程序";
        }else {
            answer = "你说撒";
        }

        //3.通过输出流，写入数据到数据通道，---->通过字符流
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write(answer);
        bufferedWriter.newLine();//插入一个换行符，表示写入内容结束，注意：要求对方使用readLine()
        bufferedWriter.flush();//如果使用字符流，需要手动刷新，否则数据不会写入

        //6.关闭流和socket
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端退出");

    }
}
